<?php
/**
 * H5活动的中间件
 * panglishan
 * 2020.10.18
 */

namespace App\Http\Middleware;

use App\Exceptions\BasicException;
use App\Http\Controllers\App\Rebuild\PublicApiController;
use App\Services\Tools\JwtService;
use Closure;


class ActivityMiddleware {

    public function handle($request, Closure $next) {
        $token = $request->header('token','');
        if (env('APP_ENV') != 'production' && is_numeric($token)) {
            $user_id = $token;
        } else {
            $user_id = JwtService::getUid($token, true);
        }
        // 验证是否被封
        $seal_time = app('redis')->get('u:seal:' . $user_id);
//        if($seal_time){
//            throw new BasicException(10008,'您的账号被封');
//        }
        if($seal_time > 0) {
            app('model_user_seal')->checkSealTime((int)$user_id);
        }
        //$user_id = JwtService::getUid($token, true);

        /*用户设备封禁*/
        $deviceId = $request->server('HTTP_DEVICEID');
        if ($deviceId) {
            $this->checkUserDevice($deviceId);
        }
        /*用户ip封禁*/
        $ip = get_real_ip();
        if ($ip) {
            $this->checkUserDeviceIp($ip);
        }

        if (!defined('UID')) {
            define('UID', $user_id);
        }

        return $next($request);
    }

    /**用户设备封禁
     * @param $deviceId
     * @throws BasicException
     */
    public function checkUserDevice($deviceId)
    {
        $is_device = app('redis')->sismember('seal:device', $deviceId);
        if ($is_device) {
//            throw new BasicException(10008, "登录设备被封，暂时无法登录");
            app('model_user_seal')->checkSealTime((int)UID, 2, '登录设备被封，暂时无法登录');
        }
    }

    /**用户ip封禁
     * @param $deviceId
     * @throws BasicException
     */
    public function checkUserDeviceIp($ip)
    {
        $is_device = app('redis')->sismember('seal:ip', $ip);
        if ($is_device) {
//            throw new BasicException(10008, "登录ip被封，暂时无法登录");
            app('model_user_seal')->checkSealTime((int)UID, 2, '登录ip被封，暂时无法登录');
        }
    }
}
